package cn.edu.scau.common.config;


import cn.edu.scau.common.setting.IShiroConst;
import cn.edu.scau.common.utils.TokenUserRedisUtils;
import cn.edu.scau.pojo.entity.UserEntity;
import cn.edu.scau.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;


import java.util.List;

/**
 * Token 认证-授权 Realm
 *
 * @className: MyRealm
 * @description
 * @author: luffy
 * @date: 2020/6/8 21:40
 * @version:V1.0
 */
public class MyRealm extends AuthorizingRealm {


    @Autowired
    private UserService userService;

    @Override
    public String getName() {
        return IShiroConst.TOKEN_REALM_NAME;
    }

    /**
     * 认证 - 登录
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        MyAuthToken authToken = (MyAuthToken) authenticationToken;
        String token = authToken.getToken();
        /**
         * 存缓存中获取token token为key,uid为value
         */
        if (StringUtils.isEmpty(token) || !TokenUserRedisUtils.isExistedKey(token) || StringUtils.isEmpty(TokenUserRedisUtils.getValueByKey(token))){
            throw new IncorrectCredentialsException("token失效，请重新登录");
        }
        Integer uid = TokenUserRedisUtils.getValueByKey(token);
        assert uid != null;
        UserEntity user =  userService.findUserEntityById(uid);
        if (user == null){
            throw new UnknownAccountException("用户不存在!");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, token, getName());
        return info;
    }

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        if (principalCollection == null) {
            throw new RuntimeException("principalCollection is null!");
        }
        UserEntity user = (UserEntity) getAvailablePrincipal(principalCollection);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //查找授权信息 略
        return info;
    }
}

